#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Excel数据查找模块 - 人员信息查询
负责从Excel文件中查找人员基本信息
"""

import os
import pandas as pd
from core.data_processor import clean_text_field
from app.config import APP_SETTINGS


class ExcelLookup:
    """Excel数据查找器"""
    
    def __init__(self, excel_file_path=None):
        """初始化Excel查找器
        
        Args:
            excel_file_path: Excel文件路径
        """
        self.excel_data = None
        self.excel_file_path = excel_file_path
        
        # 加载Excel数据
        if excel_file_path and os.path.exists(excel_file_path):
            self.load_excel_data()
        elif not excel_file_path:
            # 尝试使用默认路径
            default_path = APP_SETTINGS['DEFAULT_EXCEL_PATH']
            if os.path.exists(default_path):
                self.excel_file_path = default_path
                self.load_excel_data()
    
    def load_excel_data(self):
        """加载Excel文件数据"""
        try:
            sheet_name = APP_SETTINGS['EXCEL_SHEET_NAME']
            # 读取指定工作表
            self.excel_data = pd.read_excel(self.excel_file_path, sheet_name=sheet_name)
            print(f"已加载Excel数据，共{len(self.excel_data)}行")
        except Exception as e:
            print(f"加载Excel文件失败: {e}")
            self.excel_data = None
    
    def lookup_person_info(self, sample_id):
        """根据样品编号查找人员信息
        
        Args:
            sample_id: 样品编号（个人剂量章编号）
            
        Returns:
            tuple: (性别, 身份证号)
        """
        gender = ""
        id_card = ""
        
        if self.excel_data is not None and sample_id:
            try:
                # 在Excel中查找匹配的个人剂量章编号
                matches = self.excel_data[self.excel_data['个人剂量章编号'] == sample_id]
                if not matches.empty:
                    # 获取第一个匹配的记录
                    person_info = matches.iloc[0]
                    gender = clean_text_field(person_info.get('性别', ''))
                    id_card = clean_text_field(person_info.get('居民身份证号码', ''))
            except Exception as e:
                print(f"查找人员信息失败: {e}")
        
        return gender, id_card
    
    def is_available(self):
        """检查Excel数据是否可用
        
        Returns:
            bool: 数据是否可用
        """
        return self.excel_data is not None
    
    def get_sample_count(self):
        """获取Excel中的样品总数
        
        Returns:
            int: 样品总数
        """
        if self.excel_data is not None:
            return len(self.excel_data)
        return 0
    
    def search_by_name(self, name):
        """根据姓名搜索人员信息
        
        Args:
            name: 姓名
            
        Returns:
            list: 匹配的人员信息列表
        """
        results = []
        if self.excel_data is not None and name:
            try:
                # 查找姓名匹配的记录
                matches = self.excel_data[self.excel_data['工作人员姓名'].str.contains(name, na=False)]
                for _, person in matches.iterrows():
                    results.append({
                        '个人剂量章编号': clean_text_field(person.get('个人剂量章编号', '')),
                        '工作人员姓名': clean_text_field(person.get('工作人员姓名', '')),
                        '性别': clean_text_field(person.get('性别', '')),
                        '居民身份证号码': clean_text_field(person.get('居民身份证号码', ''))
                    })
            except Exception as e:
                print(f"按姓名搜索失败: {e}")
        
        return results
